package common;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerCacheUtil {
    private FreeMarkerConfigurer configuration;
    //工具类是单例的，ThreadLocal保证每个用户都有自己的独一份数据
    private ThreadLocal<Map> datas=new ThreadLocal<>();

    private String cacheFTLPath;


    //使用set方式对两个属性进行依赖注入，设置configuration和要存储静态文件的路径
    public void setCacheFTLPath(String cacheFTLPath) {
        this.cacheFTLPath = cacheFTLPath;
    }

    public void setConfiguration(FreeMarkerConfigurer configuration) {
        this.configuration = configuration;
        configuration.getConfiguration().setDefaultEncoding("UTF-8");
    }

    public void addAttribute(String key, Object value){

        Map map = datas.get();

        if (map==null) {
            datas.set(new HashMap());
        }
        datas.get().put(key, value);

    }

    public boolean processFtlCache(String ftlName, Writer out,String cacheKey) throws Exception{
        //不同的商品生成不同的文件
        ftlName=cacheKey+ftlName;
        File dir=new File(cacheFTLPath);
        //如果没有此文件夹，说明静态文件还没有生成。就要走三层结构拿动态页面
        if (!dir.exists()) {
            dir.mkdirs();
            return false;
        }
        //1.全部的模板文件，看要找的商品的静态页面是否在模板文件里，如果在就用流读并写出去
        String[] allftls = dir.list();
        boolean contains = Arrays.asList(allftls).contains(ftlName);
        if (contains) {
            File ftl=new File(dir,ftlName);
            BufferedReader bufferedReader=new BufferedReader(new FileReader(ftl));
            StringBuilder stringBuilder=new StringBuilder();
            String temp=null;
            while ((temp=bufferedReader.readLine())!=null){
                stringBuilder.append(temp);
            }
            out.write(stringBuilder.toString());
            return true;
        }

        return false;
    }

    public void  processFtl(String ftlName, Writer out,String cacheKey) throws Exception {
        //加载模板文件
        Template t1 = configuration.getConfiguration().getTemplate(ftlName);
        //根据模板文件生成动态页面
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        t1.process(datas.get(), new OutputStreamWriter(byteArrayOutputStream));
        t1.setOutputEncoding("UTF-8");

        //转储本地静态文件
        String ftlContents = byteArrayOutputStream.toString();
        File dir=new File(cacheFTLPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(new File(dir,cacheKey+ftlName)));
        bufferedWriter.write(ftlContents);
        bufferedWriter.close();

        //把动态页面数据返回给浏览器
        out.write(ftlContents);
        out.flush();
    }
    public void delCacheFtl(String cacheKey){
        File file=new File(cacheFTLPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File realFile=new File(file,cacheKey+"item.ftl");
        realFile.delete();

    }
}

